import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataVisualizationService } from '../dataVisualization.service';
import { TranslateService } from '@ngx-translate/core';
import { RoadCondition } from 'app/pages/data-visualization/traffic-analytics/three-roads/three-roads.component';
import { ToolsService } from 'app/shared/service';

@Component({
    selector: 'itmp-traffic-analytics',
    templateUrl: './traffic-analytics.component.html',
    styleUrls: ['./traffic-analytics.component.css']
})
export class TrafficAnalyticsComponent implements OnInit, OnDestroy {
    enteringCity: any;
    goingoutCity: any;
    realTimeTraffic: any;
    curRatio: any;
    yesterdayRatio: any;
    smoothRoads: any;
    congestionRoads: any;
    vehicleFlow: any;
    lastInfo: any;
    timer = [];

    constructor(private ds: DataVisualizationService, private translate: TranslateService, private tools: ToolsService) {}

    ngOnInit() {
        this.translate.onLangChange.subscribe(() => this._getData());
        this._getData();
        this.refreshByOneHour();
    }

    refreshByOneHour() {
        const time0 = setInterval(() => {
            this._getData();
        }, 1000 * 60 * 60);
        this.timer.push(time0);
    }

    ngOnDestroy() {
        this.timer.forEach(item => {
            clearInterval(item);
        });
    }

    _getData() {
        this.ds.getIncidentAnalyticsReport(201).subscribe(res => {
            if (res.messagecode === '000000') {
                const vehicleFlow = res.data.filter(currentValue => currentValue.selectedType === 'volofclass');
                this._getVehicleData(vehicleFlow);
                const realTimeTraffic = res.data.filter(currentValue => {
                    return currentValue.selectedType === 'realTime';
                });
                this._getRealTimeTrafficData(realTimeTraffic);
                const theMostRoads = res.data.filter(currentValue => currentValue.selectedType === 'theMost');
                this._getTheMostRoads(theMostRoads);
                const ratio = res.data.filter(currentValue => currentValue.selectedType === 'congestion');
                this._getRatio(ratio);
                const goingoutCity = res.data.filter(currentValue => currentValue.selectedType === 'goingOutCity');
                this._getGoingCity(goingoutCity, 'goingoutCity');
                const enteringCity = res.data.filter(currentValue => currentValue.selectedType === 'enteringCity');
                this._getGoingCity(enteringCity, 'enteringCity');
            }
        });
        this.lastInfo = {
            squareOfCity: '1200km²',
            expresswayNo: 40,
            expresswayMiles: '500km',
            arterialRoadNo: 100,
            arterialRoadMiles: '1500km'
        };
    }

    _getGoingCity(data, name) {
        this[name] = [0, 0];
        data.forEach(item => {
            if (item.nameType === 'today') {
                this[name][0] = +item.total;
            } else if (item.nameType === 'yesterday') {
                this[name][1] = +item.total;
            }
        });
    }

    // Vehicle flow comparison
    _getVehicleData(data) {
        const tempTranslate = ['Wagon flow', 'medium-size car flow', 'Car flow'];
        const translateData = [];
        tempTranslate.forEach(item => {
            this.translate.get('Data_Visualization.TrafficAnalytics.' + item).subscribe((res: string) => {
                translateData.push(res);
            });
        });
        setTimeout(() => {
            this.vehicleFlow = [];
            data.forEach(item => {
                const tempName =
                    item.nameType === 'Wagon flow'
                        ? translateData[0]
                        : item.nameType === 'medium-size car flow'
                            ? translateData[1]
                            : item.nameType === 'Car flow' ? translateData[2] : item.nameType;
                this.vehicleFlow.push({
                    value: item.total,
                    name: this.tools.getCapitalLetters(tempName)
                });
            });
        });
    }

    // Real-Time Traffic flow in city
    _getRealTimeTrafficData(data) {
        const xAxis = [];
        const lastday = [],
            thisday = [];
        for (let i = 0; i < 24; i++) {
            xAxis.push(`${i + 1}:00`);
            lastday.push(0);
            thisday.push(0);
        }
        data.forEach(item => {
            if (item.nameType === 'today') {
                thisday[item.Hour - 1] = item.total;
            } else if (item.nameType === 'yesterday') {
                lastday[item.Hour - 1] = item.total;
            }
        });
        this.realTimeTraffic = {
            lastday,
            thisday,
            xAxis
        };
    }

    // The most three roads
    _getTheMostRoads(data) {
        this.congestionRoads = [];
        this.smoothRoads = [];
        const cols = ['type', 'avg_speed', 'road'];
        const datas = data.map(d => [RoadCondition[d.nameType], d.avg_speed, d.roadName]);
        this.smoothRoads = [cols, ...datas].sort((a, b) => a[1] - b[1]);
        /*data.forEach(item => {
            if (item.nameType === 'heavy') {
                this.congestionRoads.push({
                    name: item.roadName,
                    value: item.avg_speed
                });
            } else {
                this.smoothRoads.push({
                    name: item.roadName,
                    value: item.avg_speed
                });
            }
        });*/
    }

    // road congestion ratio
    _getRatio(data) {
        const tempTranslate = ['Heavy', 'Jam', 'Smooth'];
        /*const translateData = [];
        tempTranslate.forEach(item => {
            this.translate.get('Data_Visualization.TrafficAnalytics.' + item).subscribe((res: string) => {
                translateData.push(res);
            });
        });*/
        const map = {};
        data.forEach(d => {
            map[d.nameType] = d;
        });
        const cols = ['type', ...tempTranslate];
        const types = data.map(d => d.nameType);
        const datas = types.map(t => [
            t,
            this.tools.toFixed(+map[t].heavy / +map[t].total * 100, 2),
            this.tools.toFixed(+map[t].jam / +map[t].total * 100, 2),
            this.tools.toFixed(+map[t].smooth / +map[t].total * 100, 2)
        ]);
        this.curRatio = [cols, ...datas];
        /*data.forEach(item => {
            if (item.nameType === 'Current') {
                this.curRatio = [
                    {value: item.smooth, name: translateData[0]},
                    {value: item.jam, name: translateData[1]},
                    {value: item.heavy, name: translateData[2]}
                ];
            } else {
                this.yesterdayRatio = [
                    {value: item.smooth, name: translateData[0]},
                    {value: item.jam, name: translateData[1]},
                    {value: item.heavy, name: translateData[2]}
                ];
            }
        });*/
    }
}
